﻿#include "responesutils.h"

#include <QJsonDocument>
#include <QJsonObject>


ResponesUtils::ResponesUtils()
{

}

ResponesUtils::~ResponesUtils()
{

}

void ResponesUtils::useResponseSuccess(stefanfrings::HttpResponse &response, QJsonObject data)
{
    QJsonObject obj;
    obj.insert("code",0);
    obj.insert("data",data);
    obj.insert("error",QJsonValue());
    obj.insert("message","ok");
    response.write(QJsonDocument(obj).toJson());
}

void ResponesUtils::useResponseSuccess(HttpResponse &response, QJsonArray data)
{
    QJsonObject obj;
    obj.insert("code",0);
    obj.insert("data",data);
    obj.insert("error",QJsonValue());
    obj.insert("message","ok");
    response.write(QJsonDocument(obj).toJson());
}

void ResponesUtils::useResponseSuccess(HttpResponse &response, QJsonValue data)
{
    QJsonObject obj;
    obj.insert("code",0);
    obj.insert("data",data);
    obj.insert("error",QJsonValue());
    obj.insert("message","ok");
    response.write(QJsonDocument(obj).toJson());
}

void ResponesUtils::usePageResponseSuccess(HttpResponse &response, uint64_t total, QJsonArray list){

    QJsonObject obj;
    obj.insert("items",list);
    obj.insert("total",QJsonValue::fromVariant(total));
    useResponseSuccess(response,obj);
}

void ResponesUtils::useResponseError(HttpResponse &response,QString message,QJsonValue error){
    QJsonObject obj;
    obj.insert("code",-1);
    obj.insert("data",QJsonValue());
    obj.insert("error",error);
    obj.insert("message",message);
    qDebug() << "ResponseError" << QJsonDocument(obj).toJson();
    response.write(QJsonDocument(obj).toJson());
}

void ResponesUtils::paramErrorResponse(HttpResponse &response, QString message)
{
    response.setStatus(404);
    useResponseError(response,message,message);
}

void ResponesUtils::forbiddenResponse(HttpResponse &response,QString message){
    response.setStatus(403);
    useResponseError(response,message,message);
}

void ResponesUtils::unAuthorizedResponse(HttpResponse &response)
{
    response.setStatus(401);
    useResponseError(response,"Unauthorized Exception", "Unauthorized Exception");
}
